#include "dev_uart.h"
#define UART_RX_LEN	 128
char UART_RXBuffer[UART_RX_LEN] = {0};
uint32_t UART_RXIndex = 0;
uint8_t uart_ide_flag = 0;
void serial_init(void)
{
    UART_InitStructure UART_initStruct;

    PORT_Init(PORTC, PIN2, FUNMUX0_UART0_RXD, 1); //GPIOC.2配置为UART0输入引脚
    PORT_Init(PORTC, PIN3, FUNMUX1_UART0_TXD, 0); //GPIOC.3配置为UART0输出引脚
#if 0
    UART_initStruct.Baudrate = 115200;
    UART_initStruct.DataBits = UART_DATA_8BIT;
    UART_initStruct.Parity = UART_PARITY_NONE;
    UART_initStruct.StopBits = UART_STOP_1BIT;
    UART_initStruct.RXThresholdIEn = 0;
    UART_initStruct.TXThresholdIEn = 0;
    UART_initStruct.TimeoutIEn = 0;
#endif
 	UART_initStruct.Baudrate = 115200;
	UART_initStruct.DataBits = UART_DATA_8BIT;
	UART_initStruct.Parity = UART_PARITY_NONE;
	UART_initStruct.StopBits = UART_STOP_1BIT;
	UART_initStruct.RXThreshold = 10;
	UART_initStruct.RXThresholdIEn = 1;
	UART_initStruct.TXThreshold = 3;
	UART_initStruct.TXThresholdIEn = 0;
	UART_initStruct.TimeoutTime = 10;		//10个字符时间内未接收到新的数据则触发超时中断
	UART_initStruct.TimeoutIEn = 1;
    UART_Init(UART0, &UART_initStruct);
    UART_Open(UART0);
}

void UART0_Handler(void)
{
	uint32_t chr;

	if((UART_INTRXThresholdStat(UART0)) || UART_INTTimeoutStat(UART0))
	{
		while(UART_IsRXFIFOEmpty(UART0) == 0)
		{
			uart_ide_flag = 0;
			if(UART_ReadByte(UART0, &chr) == 0)
			{
				if(UART_RXIndex < UART_RX_LEN)
				{
					UART_RXBuffer[UART_RXIndex] = chr;
					
					UART_RXIndex++;
				}
			}
		}
		if(UART_INTTimeoutStat(UART0))
		{
			uart_ide_flag = 1;	
		}
	}

}

uint8_t get_uart_data(uint8_t *data,uint32_t *len)
{
	uint8_t status;
#if 0
	if(uart_ide_flag)
	{
		if(UART_RXIndex)
		{
			memcpy(data,UART_RXBuffer,UART_RXIndex);
			*len = UART_RXIndex;
			status = 1;
		}
		else
		{
			status = 0;
		}
	}
	else
	{
		status = 0;
	}
	return status;
#endif
	
	if(UART_RXIndex != 0)
	{
		NVIC_DisableIRQ(UART0_IRQn);		//从UART_RXBuffer读取数据过程中要关闭中断，防止读写混乱
		memcpy(data, UART_RXBuffer, UART_RX_LEN);
		*len = UART_RXIndex;
		UART_RXIndex = 0;
		NVIC_EnableIRQ(UART0_IRQn);
		status = 1;
		
	}
	else
	{
		status = 0;
	}
	return status;
}

void set_clear_index(void)
{
	UART_RXIndex = 0;
}
/****************************************************************************************************************************************** 
* 函数名称: fputc()
* 功能说明: printf()使用此函数完成实际的串口打印动作
* 输    入: int ch  要打印的字符
*           FILE *f 文件句柄
* 输    出: 无
* 注意事项: 无
******************************************************************************************************************************************/
int fputc(int ch, FILE *f)
{
    UART_WriteByte(UART0, ch);

    while (UART_IsTXBusy(UART0))
        ;

    return ch;
}
